package cn.zs.supply.common.core.security.simple;

import cn.zs.supply.common.annotation.UserAnnotation;
import cn.zs.supply.common.core.login.LoginContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


@Component
public class JwtUserDetailServiceImpl implements UserDetailsService {

    private final PasswordEncoder passwordEncoder;
    @Autowired
    private GetUse getUse;

    @Autowired
    public JwtUserDetailServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    /** 数据库查询
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Use use=new Use();
        use.setUsername(username);
        if(username==null||username.equals("")){
            return null;
        }
        use=getUse.getUse(use);
        if(use.getPassword()==null||use.getPassword().equals("")){
            return null;
        }
        else{
            LoginContext.get().setObject(use.getObject());
            return new JwtUser(username, passwordEncoder.encode(use.getPassword()));
        }
     }
}
